<template>
  <div class="tide-container">
    <canvas ref="canvas" class="wave-canvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { invoke } from '@tauri-apps/api/core';

const canvas = ref(null);
const waterHeightPercent = ref(0);
let animationFrameId = null;
let pollInterval = null;
let ctx = null;
let totalSeconds = 25 * 60; // 默认值，稍后更新

// 波浪配置
const waves = [
  {
    y: 0,
    length: 0.01, // 波长
    amplitude: 15, // 振幅
    speed: 0.05,   // 速度
    offset: 0,     // 相位偏移
    color: 'rgba(59, 130, 246, 0.2)' // 颜色
  },
  {
    y: 0,
    length: 0.008,
    amplitude: 20,
    speed: 0.04,
    offset: 2,
    color: 'rgba(37, 99, 235, 0.2)'
  },
  {
    y: 0,
    length: 0.015,
    amplitude: 10,
    speed: 0.06,
    offset: 4,
    color: 'rgba(29, 78, 216, 0.2)'
  }
];

const updateWaterHeight = async () => {
  try {
    const remaining = await invoke('get_remaining_time');
    
    const elapsed = totalSeconds - remaining;
    const percentage = (elapsed / totalSeconds) * 100;
    
    // 目标高度百分比
    waterHeightPercent.value = Math.max(5, Math.min(100, percentage));
  } catch (e) {
    console.error('Failed to update water height:', e);
  }
};

const draw = () => {
  if (!ctx || !canvas.value) return;

  const width = canvas.value.width;
  const height = canvas.value.height;

  // 清除画布
  ctx.clearRect(0, 0, width, height);

  // 计算当前水位的基础 Y 坐标 (从底部向上)
  const targetY = height * (1 - waterHeightPercent.value / 100);
  
  // 绘制每一层波浪
  for (let i = 0; i < waves.length; i++) {
    const wave = waves[i];
    ctx.beginPath();
    ctx.moveTo(0, height); // 左下角

    // 绘制正弦波
    for (let x = 0; x <= width; x += 5) { // 步长 5px 提高性能
      // y = A * sin(Bx + C) + D
      const y = wave.amplitude * Math.sin(x * wave.length + wave.offset) + targetY;
      ctx.lineTo(x, y);
    }

    ctx.lineTo(width, height); // 右下角
    ctx.lineTo(0, height);     // 左下角闭合
    ctx.fillStyle = wave.color;
    ctx.fill();

    // 更新相位，防止数值过大导致精度问题
    wave.offset = (wave.offset + wave.speed) % (2 * Math.PI);
  }

  animationFrameId = requestAnimationFrame(draw);
};

const handleResize = () => {
  if (canvas.value) {
    canvas.value.width = window.innerWidth;
    canvas.value.height = window.innerHeight;
    // 重新获取 context 以防万一（通常不需要，但作为保险）
    ctx = canvas.value.getContext('2d');
  }
};

onMounted(async () => {
  handleResize();
  window.addEventListener('resize', handleResize);
  
  // 初始化 context
  if (canvas.value) {
    ctx = canvas.value.getContext('2d');
  }

  // 启动动画循环
  draw();

  // 获取一次总时长配置
  try {
    const settings = await invoke('get_settings');
    totalSeconds = settings.work_duration * 60;
  } catch (e) {
    console.error('Failed to get settings:', e);
  }

  // 初始数据更新
  await updateWaterHeight();
  pollInterval = setInterval(updateWaterHeight, 1000);
  
  // 显示窗口
  setTimeout(async () => {
    try {
      await invoke('show_overlay_window');
    } catch (e) {
      console.error('Failed to show overlay window:', e);
    }
  }, 100);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
  }
  if (pollInterval) {
    clearInterval(pollInterval);
  }
});
</script>

<style scoped>
.tide-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 9999;
}

.wave-canvas {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
